package Controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.torque.NoRowsException;
import org.apache.torque.TooManyRowsException;
import org.apache.torque.TorqueException;

import Models.Etudiant;
import Models.EtudiantPeer;
import Models.Groupe;
import Models.GroupePeer;

@SuppressWarnings("serial")
public class EtudiantsController extends MainController {
	
	String listView, addView, viewView, errorView, searchView;
	
	// INIT
	public void init() throws ServletException {
		this.listView 	= this.getInitParameter("view_list");
		this.addView 	= this.getInitParameter("view_add");
		this.viewView 	= this.getInitParameter("view_view");
		this.errorView 	= this.getInitParameter("view_error");
//		this.searchView = this.getInitParameter("view_search");
	}
	
	// POST
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String method = request.getMethod().toLowerCase();
		String action = request.getPathInfo();
		if (action == null) {
			action = "/";
			System.out.println("action == null");
		}
		if (method.equals("post") && action.equals("/add")) {
			request.setAttribute("title", "Ajouter un étudiant");
			this.add(request, response);
		} else if (method.equals("post") && action.equals("/list")) {
			request.setAttribute("title", "Liste des étudiants");
			this.list(request, response);
		}
	}
	
	// GET
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// On récupère la méthode d'envoi de la requête
		String method = request.getMethod().toLowerCase();
		
		// On récupère l'action à exécuter
		String action = request.getPathInfo();
		if (action == null) {
			action = "/";
			System.out.println("action == null");
		}
		
		if (method.equals("get") && action.equals("/list")) {
			request.setAttribute("title", "Liste des étudiants");
			this.list(request, response);
		} else if (method.equals("get") && action.equals("/add")) {
			request.setAttribute("title", "Ajouter un étudiant");
			this.add(request, response);
		} else if (method.equals("get") && action.equals("/view")) {
			this.view(request, response);
		} else if (method.equals("get") && action.equals("/delete")) {
			this.delete(request, response);
		} else if (method.equals("get") && action.equals("/edit")) {
			request.setAttribute("title", "Editer un étudiant");
			this.edit(request, response);
		}
//		} else if (method.equals("get") && action.equals("/search")) {
//			request.setAttribute("title", "Rechercher un étudiant");
//			this.search(request, response);
//		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Etudiant> etuList = new ArrayList<Etudiant>();
		if (request.getParameter("search") == null) {
			etuList = EtudiantPeer.doSelectAll();
		} else {
			etuList = EtudiantPeer.doSelectAll(request.getParameter("search"));
		}

		request.setAttribute("etuList", etuList);
		this.loadJSP(this.listView, request, response);
	}
	
	private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id_etudiant = Integer.parseInt(request.getParameter("e"));
		List<Groupe> grpList = new ArrayList<Groupe>();
		grpList = GroupePeer.doSelectAll();
		request.setAttribute("groupes", grpList);
		try {
			Etudiant etudiant = EtudiantPeer.retrieveByPK(id_etudiant);
			request.setAttribute("editetudiant", etudiant);
			this.loadJSP(this.addView, request, response);
		} catch (NoRowsException e) {
			e.printStackTrace();
		} catch (TooManyRowsException e) {
			e.printStackTrace();
		} catch (TorqueException e) {
			e.printStackTrace();
		}		
	}	
	
	
	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		List<Groupe> grpList = new ArrayList<Groupe>();
		HashMap<String, String> errors = new HashMap<String, String>();
		HashMap<String, String> values = new HashMap<String, String>();
		
		grpList = GroupePeer.doSelectAll();
		
		if( request.getParameter("submit") != null ) {
			if( request.getParameter("groupe").isEmpty() ) {
				errors.put("groupe", "Le groupe doit être choisi ! ");
			} else {
				values.put("groupe", request.getParameter("groupe"));
			}
			if( request.getParameter("nom").isEmpty() ) {
				errors.put("nom", "Le nom doit être saisi ! ");
			} else {
				values.put("nom", request.getParameter("nom"));
			}
			if( request.getParameter("prenom").isEmpty() ) {
				errors.put("prenom", "Le prénom doit être saisi ! ");
			} else {
				values.put("prenom", request.getParameter("prenom"));
			}
			if( errors.isEmpty() ) {
				Etudiant etudiant = null;
				try {
					if( request.getParameter("id_etudiant").equals("0") ) {
						etudiant = new Etudiant();
					} else {
						etudiant = EtudiantPeer.retrieveByPK( Integer.parseInt(request.getParameter("id_etudiant")) );
					}
					etudiant.setIdGroupe(Integer.parseInt(request.getParameter("groupe")));
					etudiant.setNom(request.getParameter("nom"));
					etudiant.setPrenom(request.getParameter("prenom"));
					etudiant.save();
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (TorqueException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				errors.clear();
				values.clear();
				request.setAttribute("etudiant", etudiant);
				request.setAttribute("groupes", grpList);
				this.loadJSP(this.addView, request, response);
			} else {
				request.setAttribute("groupes", grpList);
				request.setAttribute("errors", errors);
				request.setAttribute("values", values);
				this.loadJSP(this.addView, request, response);
			}
		} else {
			request.setAttribute("groupes", grpList);
			this.loadJSP(this.addView, request, response);
		}
	}
	
//	private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		request.setAttribute("etu", new ArrayList<Etudiant>());
//		if (request.getParameter("search") != null) {
//			ArrayList<Etudiant> etu = EtudiantPeer.doSelectLike(request.getParameter("nom"));
//			request.setAttribute("etu", etu);
//		}
//		this.loadJSP(this.searchView, request, response);
//	}
	
	private void view(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id_etudiant = Integer.parseInt(request.getParameter("etudiant"));
		
		Etudiant etu = new Etudiant();
		try {
			etu = EtudiantPeer.retrieveByPK(id_etudiant);
		} catch (NoRowsException e) {
			e.printStackTrace();
		} catch (TooManyRowsException e) {
			e.printStackTrace();
		} catch (TorqueException e) {
			e.printStackTrace();
		}
		
		request.setAttribute("etudiant", etu);
		request.setAttribute("title", etu.toString()+" - Etudiant");
		this.loadJSP(this.viewView, request, response);
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id_etudiant = Integer.parseInt(request.getParameter("e"));
		
		Etudiant etu = new Etudiant();
		try {
			etu = EtudiantPeer.retrieveByPK(id_etudiant);
			EtudiantPeer.doDelete(etu);
			request.setAttribute("title", "Liste des étudiants");
			this.list(request, response);
		} catch (NoRowsException e) {
			request.setAttribute("title_error", "Erreur suppression");
			request.setAttribute("message", "Etudiant non trouvé");
			this.loadJSP(this.errorView, request, response);
		} catch (TooManyRowsException e) {
			e.printStackTrace();
		} catch (TorqueException e) {
			e.printStackTrace();
		}
	}
}
